package com.example.httptest.service;

import com.example.httptest.entity.User;
import com.example.httptest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class UserService {

    @Autowired
    UserRepository userRepository;

    public boolean register(String userName, String password, String nickName){
        List<User> users = userRepository.findAll();
        for (User user : users) {
            //注意不要用 ==, 用equals
            if(user.getUserName().equals(userName))          //如果userId重复，则返回注册失败
                return false;
        }

        //不重复则对其进行注册
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setNickName(nickName);
        try {
            userRepository.saveAndFlush(user);
        }catch (Exception e)
        {
            return false;
        }

        return true;
    }

    public User loginCheck(String userName,String password){
        return userRepository.findUserByUserNameAndPassword(userName,password);
    }


}
